<template>
  <div class="invitation-main">
     <!-- 页头 -->
    <PageHeader :lang="lang"></PageHeader>
    <div class="banner banner-big">
      <img :src="textData.Img" class="maxBanner">
      <div class="words">
        <img src="./images/logo.png">
        <h3>{{textData && textData.Banner1}}</h3>
        <p>{{textData && textData.Banner2}}</p>
      </div>
    </div>
     <div class="banner banner-small">
      <img :src="textData.Banner800" class="maxBanner">
      <div class="words">
        <img src="./images/logo.png">
        <h3>{{textData && textData.Banner1}}</h3>
        <p>{{textData && textData.Banner1}}</p>
      </div>
    </div>

    <div class="section">
      <div class="title"> {{textData && textData.Text1}}</div>

      <div class="menu">
        <a :class="{active: isPhone}" @click="isPhone=true">{{lang.invite1}}</a>  <a :class="{active: !isPhone}" @click="isPhone=false">{{lang['login eamil number']}}</a>
      </div>

      <div class="control-main">

        <div class="control-item area-item" v-show="isPhone">
          <span class="area" :class="{active: areaCode}" @click.stop="areaSelect"> +{{areaCode}}<font v-show="!areaCode">000</font></span>
          <input type="text"  class="inputArea" :placeholder="lang.invite2"  oninput="value=value.replace(/[^\d]/g, '')" v-model="phone">
          <div class="selectAreaList" v-show="isShowAreaList">
            <ul>
              <li v-for="item in countryList" @click="selectList(item.Areacode)">
                <span class="name">{{item.Name}}</span>
                <span class="number">{{item.Areacode ? '+' + item.Areacode : ''}}</span>
              </li>
            </ul>
          </div>
        </div>

        <div class="control-item" v-show="!isPhone">
          <input type="text" :placeholder="lang['login enter email']"  v-model="email" >
        </div>

        <div class="control-item">
          <input :type="passwordType" v-model="password" :placeholder="lang['41002']">
          <a class="showHidePassword" @click="showHidePassword" :class="{active: isShowHidePassword}"></a>
        </div>

        <div class="control-item">
          <input type="text" :placeholder="lang.register_PleaseerificationCode" v-model="verifyCode" oninput="value=value.replace(/[^\d]/g, '')" maxlength="6">
            <a class="sendCode" @click="sendMsg" :class="{active: !sendMsgDisabled}">
              {{sendMsgDisabled ? lang.invite4 :lang.invite6.replace('{time}', time)}}
            </a>
        </div>

        <div class="control-item">
          <button type="button" class="buttonBox" @click="submit" :disabled="disabledBtn">{{textData && textData.Button1Text}}</button>
          <a class="downApp" :href="textData && textData.DownloadUrl" target="_blank">{{textData && textData.DownloadText}}</a>
        </div>
      </div>

      <div class="title">
        <img :src="textData.Logo">
      </div>

      <div class="intr" v-html="textData && textData.Text2"></div>
    </div>

    <!-- 验证窗口 -->
    <div class="loginVerifySuccess" v-show="isShowVerify">
      <div class="verifyMain">
        <h3>{{lang['login Sliding verification5']}}</h3>
        <img src="./images/closeverify.png"  @click="closeVerify">
        <div id="your-dom-id" class="nc-container"></div>
      </div>
    </div>

    <SwModal :isShow.sync="isShowSuccessful"></SwModal>
    <div class="success-dig" v-show="isShowSuccessful">
    <div class="close" @click="isShowSuccessful=false"><img src="./images/close.png"></div>
    <div class="success"><img src="./images/success.png"></div>
    <div class="str" v-html="textData.SuccessMsg"></div>
    <a class="go" :href="textData && textData.DownloadUrl" target="_blank">{{lang.invite5}}<img src="./images/go.png"></a>
    <div class="downApp"><a :href="textData && textData.DownloadUrl" target="_blank">{{textData.DownloadText}}</a></div>
    </div>

    <!-- 页脚 -->
    <PageFooter2 :lang="lang" :langKey="langKey"></PageFooter2>
  </div>
</template>
<script>
import commonMixins from '@/mixins/common.js'
import { mapGetters, mapActions } from 'vuex'
import ModalApi from '@/components/SwModal/api.js'
import SwModal from '@/components/SwModal'

export default {
  mixins: [commonMixins],
  data () {
    return {
      time: 60,
      sendMsgDisabled: true,
      countryList: [],
      isShowAreaList: false,
      countryCode: '',
      areaCode: '',
      isPhone: true,
      password: '',               // 输入的密码
      passwordType: 'password',     // 文本框的类型，用于显示和隐藏密码
      isShowHidePassword: false,      // 是否显示密码图片的对应图标
      email: '',
      phone: '',
      verifyCode: '',            // 验证码
      textData: {},
      flag: false,                 // 是否可以发送验证码
      isShowVerify: false,
      behaviorCode: '',
      isShowSuccessful: false,
      codeIsExist: false,
      disabledBtn: false        // 是否禁用按钮
    }
  },
  watch: {
    langKey () {
      this.getText()
      this.initCountryList()
    }
  },
  computed: {
    ...mapGetters({
      langKey: 'langKey',
      mixUserInfo: 'userInfo'
    })
  },
  components: {
    SwModal
  },
  methods: {
    ...mapActions([ 'switchLang' ]),
    setScrollBar () {
      // 滚动条
      this.$nextTick(() => {
        $('.selectAreaList').niceScroll({
          autohidemode: false
        }).resize()
      })
    },
    // 显示隐藏密码
    showHidePassword () {
      this.isShowHidePassword = !this.isShowHidePassword
      this.passwordType = (this.passwordType === 'password') ? 'text' : 'password'
    },
    // 选择地区编号
    areaSelect () {
      this.isShowAreaList = !this.isShowAreaList
    },
    selectList (areaCode) {
      this.areaCode = areaCode
      this.countryCode = item.Code
      this.isShowAreaList = false
    },
    initCountryList () {
      this.$http.get('/static/js/data/country_' + this.langKey + '.json', {

      }, {
        isCustomUrl: true,
        modalOptions: {
          modalClass: 'userModal'
        }
      }).then((res) => {
        let list = []
        for (let i = 0; i < res.Data.length; i++) {
          for (let j = 0; j < res.Data[i].Data.length; j++) {
            res.Data[i].Data[j].Areacode = res.Data[i].Data[j].Areacode.replace('+', '')
            list.push(res.Data[i].Data[j])
          }
        }
        this.countryList = list
      })
    },
    hideLangList () {
      this.isShowAreaList = false
    },
    // 获取页面文言配置
    getText () {
      // console.log('window.location', window.location)
      this.$host3.post('IDCMInvite/GetInvitedPagesetting', {
        type: 2,
        host: window.location.hostname === '127.0.0.1' ? 'prewww.idcm.io' : window.location.hostname
      }).then((res) => {
        // 获取文本信息
        this.textData = res.data || ''
      })
    },
     // 发送验证码按钮事件
    sendMsg () {
      // 发送前验证下手机或者邮箱的格式
      if (!this.checkFormat()) {
        return
      }
      // 判断手机号或者邮箱是否注册
      this.isPhone ? this.checkPhone() : this.checkEmail()
    },

    // 验证手机号是否被注册
    checkPhone () {
      this.$host1.post('Customer/IsExistPhone', {
        areaCode: this.areaCode,
        phone: this.phone
      }).then((res) => {
        if (res.StatusCode === '200') {
          // 开启滑块
          this.isShowVerify = true
        } else if (res.StatusCode === '51006') {
          ModalApi.message(this.lang['51006'])
        }
      })
    },
    // 验证邮箱是否被注册
    checkEmail () {
      this.$host1.post('Customer/IsExistEmail', {
        email: this.email
      }).then((res) => {
        if (res.StatusCode === '200') {
          // 开启滑块
          this.isShowVerify = true
        } else if (res.StatusCode === '51007') {
          ModalApi.message(this.lang['51007'])
        }
      })
    },

    closeVerify () {
      this.isShowVerify = false
      this.aliyun()
    },
      aliyun () {
      let self = this
      // ar_SA:阿拉伯文
      // de_DE:德文
      // es_ES:西班牙文
      // fr_FR:法文
      // in_ID:印尼语
      // it_IT:意大利文
      // iw_HE:希伯来语
      // ja_JP:日文
      // ko_KR:韓文
      // nl_NL:荷蘭文
      // pt_BR:波蘭文
      // ru_RU:俄文
      // th_TH:泰文
      // tr_TR:土耳其文
      // vi_VN:越南文
      // cn:简体中文
      // tw:繁体中文
      // en:英文
      let key = ''
      if (self.langKey === 'zh-CN') { key = 'cn'}
      if (self.langKey === 'en') { key = 'en'}
      if (self.langKey === 'zh-Hant') { key = 'tw'}
      if (self.langKey === 'fr') { key = 'fr_FR'}
      if (self.langKey === 'ja') { key = 'ja_JP'}
      if (self.langKey === 'ko') { key = 'ko_KR'}
      if (self.langKey === 'nl') { key = 'nl_NL'}
      if (self.langKey === 'vi') { key = 'vi_VN'}

      let ncToken = ['FFFF0N0000000000635A', (new Date()).getTime(), Math.random()].join(':')
      let ncOpt = {
        renderTo: '#your-dom-id',
        appkey: 'FFFF0N0000000000635A',
        scene: 'nc_login',
        token: ncToken,
        customWidth: '100%',
        trans: { 'key1': 'code0' },
        elementID: ['usernameID'],
        is_Opt: 0,
        language: key,
        isEnabled: true,
        timeout: 3000,
        times: 5,
        apimap: {
        },
        callback (data) {
          self.pcTest(data)
        }
      }
      var nc = new noCaptcha(ncOpt)
      nc.upLang(key, {
        _startTEXT: self.lang['login Sliding verification'], // '请按住滑块，拖动到最右边',
        _yesTEXT: self.lang['login Sliding verification2'], // '验证通过',
        _error300: self.lang['login Sliding verification3'], // '哎呀，出错了，点击<a href=\'javascript:__nc.reset()\'>刷新</a>再来一次',
        _errorNetwork: self.lang['login Sliding verification4'], // '网络不给力，请<a href=\'javascript:__nc.reset()\'>点击刷新</a>',
      })
    },
    pcTest (data) {
      this.$host1.post('Aliyun/PCSlider', {
        csessionid: data.csessionid,
        sig: data.sig,
        token: data.token,
        value: data.value,
        BusinessType: 1 // 0 未知类型， 1 登录， 2注册， 3 找回密码
      }).then((res) => {
        if (res.StatusCode === '200') {
          res.Data = res.Data || {}
          this.behaviorCode = res.Data.BehaviorCode || ''
          this.closeVerify()
          //  发送验证码
          this.$host1.post('Customer/SendVerifyCode', {
            verifyDeviceType: this.isPhone ? 1 : 2, // 1.手机；2.邮箱
            clientType: 0, // 0,网页; 1,android; 2,iOS
            businessType: 1,  // 1,注册; 2,找回密码
            areaCode: this.areaCode,
            phoneOrEmail: this.isPhone? this.phone : this.email,
            Code: this.behaviorCode
          })
          .then((res) => {
            if (res.StatusCode === '200') {
              ModalApi.message(this.lang['VerificationCodeSuccessful'])
              // 倒计时
              this.sendMsgDisabled = false
              let interval = window.setInterval(() => {
                this.time--
                if (this.time <= 0) {
                  this.sendMsgDisabled = true
                  this.time = 60
                  window.clearInterval(interval)
                }
              }, 1000)
              // 倒计时
            } else {
              ModalApi.message(this.lang[res.StatusCode])
            }
          })
        }
      })
    },

    // 调取发送短信接口
    send (type) {
      this.$host3.post('Customer/SendVerifyCode', {
        verifyDeviceType: type,
        clientType: 0,
        businessType: 1,
        areaCode: this.areaCode,
        phoneOrEmail: type === 1 ? this.phone : this.email,

      }).then((res) => {
        // 获取文本信息
        this.textData = res.data
      })
    },
    // 检查格式，点击发送验证码需要验证手机或者邮箱格式
    checkFormat () {
      // 手机状态下
      if (this.isPhone) {
        // 没有选择地区
        if (!this.areaCode) {
          ModalApi.message(this.lang['41006'])
          return false
        }

        // 没有输入手机号码或者手机号码格式错误
        let rule = (this.areaCode === '86') ? /^1[3456789]\d{9}$/ : /^\d+$/
        if (!this.phone || !rule.test(this.phone)) {
          ModalApi.message(this.lang['please enter the correct phone number'])
          return false
        }
      }

      // 邮箱状态下
      if (!this.isPhone) {
        let rule = /^[a-zA-Z0-9]+([._\\-]*[a-zA-Z0-9])*@([a-zA-Z0-9]+.){1,63}[a-zA-Z]+$/
        if (!this.email || !rule.test(this.email.trim())) {
          ModalApi.message(this.lang['register_EmailErr'])
          return false
        }
      }

      // 未输入密码状态时,或者密码格式错误时
      let rule = /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*?+-]+)$)^[\w~!@#$%\^&*?+-]+$/
      if (!this.password || !rule.test(this.password)) {
        ModalApi.message(this.lang['please enter the correct password'])
        return false
      }
      return true
    },

    // 禁用按钮三秒
    disBtn () {
      this.disabledBtn = true
      setTimeout(() => {
        this.disabledBtn = false
      }, 3000)
    },
    // 领取
    submit () {
      if(!this.checkFormat()) {
        this.disBtn()
        return
      }

      // 未输入验证码, 或者验证码格式错误
      let rule = /^\d{6}$/
      if (!this.verifyCode || !rule.test(this.verifyCode)) {
        ModalApi.message(this.lang['43013'])
        this.disBtn()
        return
      }
      // 禁用按钮
      this.disabledBtn = true
      let params = {
        countryCode: this.countryCode || '',  // 邮箱注册国家编码为空 陈
        areaCode: this.areaCode || '',
        phoneOrEmail: this.isPhone ? this.phone : this.email,
        password: this.password,
        verifyCode: this.verifyCode,
        verifyDeviceType: this.isPhone ? 1 : 2,  // 1.手机;2.邮箱
        InvitationCode: this.codeIsExist ? this.$route.query.code : ''
      }

      this.$http.post('Customer/RegisterUser', params).then((res) => {
        if (res.StatusCode === '200') {
          this.isShowSuccessful = true
        } else {
          ModalApi.message(this.lang[res.StatusCode])
        }
        // 启用按钮
        this.disabledBtn = false
      })
    },
    // 判断验证码是否存在
    isExistCode () {
      this.$host3.post('IDCMInvite/CustomerCodeExist', {
        code: this.$route.query.code
      }).then((res) => {
        this.codeIsExist = res.data
      })
    }
  },
  mounted () {
    // 切换对应语言
    this.switchLang(this.$route.query.lang)
    // 获取文言配置
    this.getText()
    // 获取国家列表
    this.initCountryList()
    // 验证邀请码
    this.isExistCode()
    document.addEventListener('click', this.hideLangList)
    this.aliyun()
    this.setScrollBar()
  },
  beforeDestroy () {
    document.removeEventListener('click', this.hideLangList)
  }
}
</script>

<style lang="less">
.invitation-main {
  min-width: 780px;
  .banner-small {
    display: none;
  }
  .banner{
    position: relative;
    margin-bottom: 41px;
    .maxBanner {
      display:block; 
      width:100%;
      height: 550px;
    }

    .words {
      width: 100%;
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      color: #fff;
      text-align: center;

      img {
        display: block;
        margin: 0 auto 60px;
      }

      h3{margin-bottom: 53px; line-height: 70px;  font-size: 50px;}
      p{line-height: 56px;  font-size: 40px;}
    }
  }

  .section {
    max-width: 1200px;
    margin: 0 auto;
  }
  .title {
    margin: 0 auto;
    height: 40px;
    line-height: 40px;
    background: url(images/leftLine.png) no-repeat left center, url(images/rightLine.png) no-repeat right center;
    color: #fff;
    text-align: center;

    img {
      height: 40px;
    }
  }

  .menu {
    margin-top: 36px;
    text-align: center;

    a{
      display: inline-block;
      margin: 0 50px;
      padding: 0 5px;
      line-height: 32px;
      color: #fff;
      font-size: 16px;

      &.active {
         border-bottom: solid 2px #7FBBFF;
      }
    }
  }

  .control-main {
    margin: 20px auto 0;
    width: 500px;

    .control-item {
      position: relative;
      margin-bottom: 10px;
      min-height: 50px;
      border-radius: 5px;

      &.area-item{
        background: #fff;
      }

      .area {
        float: left;
        margin-top: 10px;
        display: inline-block;
        width: 86px;
        height: 30px;
        line-height: 30px;
        border-right:solid 1px #999;
        text-align: center;
        color: #999;
        cursor: pointer;

        &.active{
          color: #333;
        }
      }

      .selectAreaList {
        position: absolute;
        top: 43px;
        z-index: 5;
        width: 100%;
        max-height: 210px;
        overflow-y: auto;
        background:#fff;
        border-radius: 5px;

        ul {
          padding: 10px 0;
        }

        li {
          padding: 0 12px;
          height: 40px;
          line-height: 40px;
          display: flex;
          justify-content:  space-between;
          cursor: pointer;

          span {
            font-size: 16px;
            color: #666;
          }

          &:hover{
            background: #CEE0FF;
            span {color: #fff}
          }
        }

      }

      input {
        padding: 0 10px 0 23px;
        width: 100%;
        height: 50px;
        line-height: 50px;
        box-sizing:  border-box;
        border-radius: 5px;
        font-size: 16px;
      }

      .inputArea { width: 409px; float: left;}

      .sendCode {
        position: absolute;
        top: 5px;
        right: 10px;
        display: inline-block;
        padding:0 5px;
        min-width: 100px;
        height: 40px;
        line-height: 40px;
        background: #031128;
        border-radius: 4px;
        font-size: 14px;
        color: #FFFFFF;
        text-align: center;

        &.active{
          background: #999;
          cursor: no-drop;
        }
      }

      .showHidePassword {
        display: block;
        position: absolute;
        top: 0;
        right: 0;
        width: 50px;
        height: 50px;
        background: url(./images/hidden.png) no-repeat center center;

        &.active {
          background: url(./images/look.png) no-repeat center center;
        }
      }

      .buttonBox {
        display: block;
        margin-top: 20px;
        width: 100%;
        height: 40px;
        line-height: 40px;
        font-size: 16px;
        background-image: linear-gradient(-225deg, #7FBBFF 0%, #4485E4 100%);
        border-radius: 6px;
        color: #fff;
      }

      .downApp {
        display: block;
        padding: 26px 0 50px;
        font-size: 16px;
        color: #fff;
        text-align: center;
      }
    }
  }
  .intr{
    width: 98%;
    max-width: 1200px;
    margin:20px auto 80px;
    line-height: 26px;
    color: #fff;
    .loginVerifySuccess {
      position: fixed;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.4);
      -webkit-box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.37);
      box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.37);
      border-radius: 10px;
      z-index: 10;
    }
  }

  .success-dig {
    width: 345px;
    height: 334px;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: url('./images/successBG.png') no-repeat;
    background-size: cover;
    z-index: 15;
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 15px;
    box-sizing: border-box;

    .close {
      width: 100%;
      text-align: right;

      img {
        width: 18px;
        height: 18px;
        cursor: pointer;
      }
    }

    .str {
      margin: 30px 0;
      text-align: center;
      font-size: 16px;
      color: #fff;
      line-height: 25px;
    }

    .go {
      display: block;
      height: 40px;
      padding: 0 20px;
      border-radius: 30px;
      background-color: #fff;
      font-size: 16px;
      display: flex;
      align-items: center;
      cursor: pointer;
      color: #333;

      img {
        width: 90px;
        height: 30px;
        margin-left: 10px;
      }

      a:visited {
        color: #333;
      }
    }

    .downApp {
      color: #fff;
      margin-top: 18px;
      font-size: 15px;
      cursor: pointer;
      a:visited {
        color: #fff;
      }
    }
  }

  ::-webkit-input-placeholder { /* WebKit browsers */
    color: rgba(0,0,0, .5);
  }
  ::-moz-placeholder { /* Mozilla Firefox 19+ */
    color: rgba(0,0,0, .5);
  }
  ::-ms-input-placeholder { /* Internet Explorer 10+ */
    color: rgba(0,0,0, .5);
  }
}

@media screen and (max-width: 1200px){
  .invitation-main {
    .banner-small {
      display: block;
    }
    .banner-big {
      display: none;
    }
    .title {
      background: url(images/leftLine-800.png) no-repeat left center, url(images/rightLine-800.png) no-repeat right center;
    }
  }
}
</style>

